package indi.mozping.service.impl;

import com.github.tobato.fastdfs.exception.FdfsServerException;
import indi.mozping.consts.CodeConst;
import indi.mozping.consts.MsgException;
import indi.mozping.dto.FileDto;
import indi.mozping.service.FileService;
import indi.mozping.util.FastClientWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;


/**
 * 文件服务
 *
 * @author lx362
 */
@Service
public class FileServiceImpl implements FileService {

    private final Logger logger = LoggerFactory.getLogger("FileServiceImpl");

    /**
     * 解析路径
     */
    private static final String SPLIT_FILE_URL_SEPERATOR = "/";

    @Autowired
    private FastClientWrapper fastDFSClientWrapper;

    @Value("${file.url.prefix}")
    private String filePriex;

   /* @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TUploadedRecordMapper tUploadedRecordMapper;

    @Autowired
    private TFileUserMapper tFileUserMapper;

    @Autowired
    private UserInfoHelper userInfoHelper;*/


    /**
     * 上传文件
     *
     * @param file     文件
     * @param isRecord 是否存记录
     * @param token    登录用户token
     * @return
     */
    @Override
    public FileDto uploadByFile(MultipartFile file, boolean isRecord, String token) {
        // 上传文件，返回fileId, 类似 group1/M00/00/00/wKhjZFsbgEGALzeKAFm1CNSDijc772.jpg
        String fileId = null;
        String fileMD5 = null;
        FileDto fileResult = new FileDto();
        Date upDate = new Date();

        fileId = uploadByFile2FileId(file);

        fileResult.setFileId(fileId);
        fileResult.setFileUrl(filePriex.endsWith("/") ? filePriex + fileId : filePriex + SPLIT_FILE_URL_SEPERATOR + fileId);
        return fileResult;
    }


    /**
     * 调用FastDfs上传文件，返回文件路径
     *
     * @param file
     * @return group1/M00/00/00/wKhjZFsbgEGALzeKAFm1CNSDijc772.jpg
     */
    private String uploadByFile2FileId(MultipartFile file) {
        if (null == file) {
            throw new MsgException(CodeConst.FILE_IS_NULL);
        }

        try {
            return fastDFSClientWrapper.uploadFile(file, null);
        } catch (FdfsServerException e) {
            logger.error("FastDFsServer upload Multipart file is error", e);
            throw new MsgException(e.getMessage(), CodeConst.FILE_UP_FAIL);
        } catch (Exception e) {
            logger.error("FileServiceImpl.uploadByFile2FileId 上传文件file失败", e);
            throw new MsgException(CodeConst.FILE_UP_FAIL);
        }
    }


}
